import * as constants from './constants';
import { fromJS } from 'immutable';

import { message } from 'antd';

import {getAllFileAxios, deleteFileAxios, downloadFileAxios} from '../../../../api/dataSource/fileManage'

const getFiles = (dataSource) => ({
  type: constants.GET_FILES,
  files: fromJS(dataSource),
});

export const getFilesOperation = () => {
  return(dispatch) => {
    getAllFileAxios().then((res) => {
      if(res){
        if(res.data.ok){
          const dataSource = res.data.data;
          dispatch(getFiles(dataSource));
        }
      }
    });
  }
};

export const getFilesSearch = (search) => {
    return(dispatch) => {
      getAllFileAxios().then((res) => {
        if(res){
          if(res.data.ok){
            const dataSource = res.data.data;
            let searchFiles = [];
            for(let i in dataSource){
                if(dataSource[i].filename.indexOf(search) >= 0 || dataSource[i].path.indexOf(search) >= 0){
                    searchFiles.push(dataSource[i])
                }
            }
            dispatch(getFiles(searchFiles));
          }
        }
      });
    }
  };

export const deleteFile = (fileId, filename) => {
    return(dispatch) => {
     deleteFileAxios({fileId, filename}).then((res) => {
        if(res){
            console.log(res)
          if(res.data.ok){
            message.success('文件删除成功！')
            dispatch(getFilesOperation());
          }
        }
      });
    }
  };

